package cn.tradewin.common.realm;

import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.slf4j.Logger;

import cn.tradewin.common.model.RolesPerms;
import cn.tradewin.pmp.persist.model.Users;
import cn.tradewin.pmp.services.TwdSecurityService;
import cn.tradewin.pmp.services.UsersService;

public class TwdJdbcSecurityRealm extends AuthorizingRealm {

	public static final String SECURITY_NAME = "TwdJdbcSecurity";
	
	@Inject
	private TwdSecurityService securityService;
	
	@Inject
	private UsersService userService;
	
//	private final CredentialsMatcher credentialsMatcher;
	
	@Inject
	Logger log;
	
	public TwdJdbcSecurityRealm(
			@InjectService("RetryLimitHashedCredentialsMatcher")
			CredentialsMatcher retryLimitMatcher) {
		super();
		this.setName(SECURITY_NAME);
//		HashedCredentialsMatcher hashedMatch = new HashedCredentialsMatcher("SHA-256");
//		this.setCredentialsMatcher(hashedMatch);
		
		this.setCredentialsMatcher(retryLimitMatcher);
		this.setCacheManager(new MemoryConstrainedCacheManager());
		
	}
	
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		if (principals == null) {
			throw new AuthorizationException("PrincipalCollection was null, which should not happen");
		}
		if (principals.isEmpty()) {
			return null;
		}
		if (principals.fromRealm(getName()).size() <= 0) {
			return null;
		}
		String username = (String) principals.fromRealm(getName()).iterator().next();
		if (username == null) {
			return null;
		}
		SimpleAuthorizationInfo info = null;
		List<RolesPerms> records = securityService.getRolesPerms(username);
		if (records != null && records.size() > 0) {
			Set<String> roles = CollectionFactory.newSet();
			Set<String> perms = CollectionFactory.newSet();
			for (RolesPerms rp : records) {
				roles.add(rp.getRoleName());
				perms.add(rp.getPermName());
			}
			info = new SimpleAuthorizationInfo();
			info.addRoles(roles);
			info.addStringPermissions(perms);
			log.debug(username + " : roles = " + roles.toString());
			log.debug(username + " : permissions = " + perms.toString());
		}
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken userToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)userToken;
		Users user = userService.getUser(token.getUsername());
		
		if (user == null) {
			throw new AuthenticationException("failure to login!");
		} else {
			// use password which stored in the database
			// token's password no need to using passwordService to encrypt.
			return new SimpleAuthenticationInfo(
					user.getUserId(),
					user.getPassword(), 
					this.getName());
		}
	}
}